<template>
	<view class="uni-container">
		<uni-forms ref="form" :model="formData" validateTrigger="bind">
			<uni-forms-item name="classname" label="名称" required>
				<uni-easyinput placeholder="分类名称" v-model="formData.classname"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="sort" label="排序">
				<uni-easyinput placeholder="分类排序" type="number" v-model="formData.sort"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item name="picurl" label="分类图标">
				<uni-file-picker file-mediatype="image" :auto-upload="false" @select="handleFileSelect" return-type="object" v-model="formData.picurl"></uni-file-picker>
			</uni-forms-item>
			<uni-forms-item name="enable" label="是否启用">
				<switch @change="binddata('enable', $event.detail.value)" :checked="formData.enable"></switch>
			</uni-forms-item>
			<uni-forms-item name="select" label="是否推荐">
				<switch @change="binddata('select', $event.detail.value)" :checked="formData.select"></switch>
			</uni-forms-item>
			<view class="uni-button-group">
				<button type="primary" class="uni-button" style="width: 100px" @click="submit" :disabled="!canSubmit">提交</button>
				<navigator open-type="navigateBack" style="margin-left: 15px">
					<button class="uni-button" style="width: 100px">返回</button>
				</navigator>
			</view>
		</uni-forms>
	</view>
</template>

<script>
import { validator } from '@/js_sdk/product_wallpaper/class.js';
import { uploadFileToDir } from '../utils.js';

const db = uniCloud.database();
const dbCmd = db.command;
const dbCollectionName = 'product_wallpaper_class';

function getValidator(fields) {
	let result = {};
	for (let key in validator) {
		if (fields.includes(key)) {
			result[key] = validator[key];
		}
	}
	return result;
}

export default {
	data() {
		let formData = {
			classname: '',
			sort: null,
			picurl: null,
			enable: true,
			select: true
		};
		return {
			canSubmit: false,
			formData,
			formOptions: {},
			rules: {
				...getValidator(Object.keys(formData))
			}
		};
	},
	onLoad(e) {
		if (e.id) {
			const id = e.id;
			this.formDataId = id;
			this.getDetail(id);
		}
	},
	onReady() {
		this.$refs.form.setRules(this.rules);
	},
	methods: {
		/**
		 * 手动上传文件
		 */
		async handleFileSelect(fileInfo) {
			uploadFileToDir(
				fileInfo,
				'wallpaper/class',
				(fileUrl) => {
					this.formData.picurl = fileUrl;
				},
				(percentCompleted) => {
					this.canSubmit = percentCompleted === 100;
				}
			);
		},
		/**
		 * 验证表单并提交
		 */
		submit() {
			uni.showLoading({
				mask: true
			});
			this.$refs.form
				.validate()
				.then((res) => {
					console.log(res);
					return this.submitForm(res);
				})
				.catch(() => {})
				.finally(() => {
					uni.hideLoading();
				});
		},

		/**
		 * 提交表单
		 */
		submitForm(value) {
			// 使用 clientDB 提交数据
			return db
				.collection(dbCollectionName)
				.doc(this.formDataId)
				.update(value)
				.then((res) => {
					uni.showToast({
						title: '修改成功'
					});
					this.getOpenerEventChannel().emit('refreshData');
					setTimeout(() => uni.navigateBack(), 500);
				})
				.catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				});
		},

		/**
		 * 获取表单数据
		 * @param {Object} id
		 */
		getDetail(id) {
			uni.showLoading({
				mask: true
			});
			db.collection(dbCollectionName)
				.doc(id)
				.field('classname,sort,picurl,enable,select')
				.get()
				.then((res) => {
					const data = res.result.data[0];
					if (data) {
						this.formData = data;
						this.canSubmit = !!data.picurl.url;
					}
				})
				.catch((err) => {
					uni.showModal({
						content: err.message || '请求服务失败',
						showCancel: false
					});
				})
				.finally(() => {
					uni.hideLoading();
				});
		}
	}
};
</script>
